package common

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"github.com/astaxie/beego/logs"
)

type ShaWithRsa struct {
	privateKey *rsa.PrivateKey
}

func (s *ShaWithRsa) SetPriKey(pkey []byte) {
	block, _ := pem.Decode(pkey)
	if block == nil {
		logs.Error("can not decode pem file content")
		return
	}
	private, err := x509.ParsePKCS8PrivateKey(block.Bytes)
	if err != nil {
		logs.Error("can not parse private key", err)
		return
	}
	s.privateKey = private.(*rsa.PrivateKey)
	return
}

func (s *ShaWithRsa) Sign(data string) string {
	h := crypto.Hash.New(crypto.SHA1)
	h.Write([]byte(data))
	hashed := h.Sum(nil)
	signature, err := rsa.SignPKCS1v15(rand.Reader, s.privateKey, crypto.SHA1, hashed)
	if err != nil {
		logs.Error("can not signature:", err)
		return ""
	}
	sig := fmt.Sprintf("%x", signature)
	return sig
}